package com.xyzwps.server.paimon.ui.viewservice

import com.xyzwps.server.paimon.model.entity.Article
import com.xyzwps.server.paimon.model.entity.User
import com.xyzwps.server.paimon.model.service.UserDomainService
import com.xyzwps.server.paimon.ui.view.ArticleView
import com.xyzwps.server.paimon.ui.view.SimpleUserView
import com.xyzwps.server.paimon.value.UserId
import org.jetbrains.exposed.v1.jdbc.transactions.transaction
import org.springframework.stereotype.Service

@Service
class ArticleViewService(
    private val userDomainService: UserDomainService
) {

    fun inject(article: Article): ArticleView {
        val author = getAuthor(article)
        return ArticleView(article, author)
    }

    fun inject(articles: List<Article>): List<ArticleView> {
        if (articles.isEmpty()) {
            return emptyList()
        }

        val userMap = getAuthorsMap(articles)
        return articles.map { a -> ArticleView(a, userMap[a.userId]) }
    }

    fun getAuthor(article: Article?): SimpleUserView? = transaction {
        if (article == null) null
        else userDomainService.getById(article.userId)?.let { SimpleUserView(it) }
    }

    private fun getAuthors(articles: List<Article>): List<User> = transaction {
        if (articles.isEmpty()) {
            return@transaction emptyList()
        }
        val userIds = articles.map { it.userId }.distinct()
        userDomainService.getByIds(userIds)
    }

    fun getAuthorsMap(articles: List<Article>): Map<UserId, SimpleUserView> {
        val authors = getAuthors(articles)
        return authors.associate { it.id!! to SimpleUserView(it) }
    }
}
